import mongodbHandle from '../handle/mongodbHandle'
import routes from './route'
var ObjectId = require('mongodb').ObjectId;
var utility = require("utility");
import app from '../app'
import * as moment from 'moment'
import * as cluster from 'cluster'
import redisHandle from '../handle/redisHandle';
import worldBossHandle from 'src/handle/worldBossHandle';
import * as request from 'request'
import { base64 } from 'src/core/enco';


routes.setUserNotLogin('setVersion', [
    ['version', 'string'],
    ['data', 'array'],
    ['modify', 'number', false],
], async (msg) => {
    let {
        version,
        data,
        modify
    } = msg
    await mongodbHandle.gameDao.updateOne({ index: 1 }, {
        $set: {
            version: version,
        }
    })
    console.log("setVersion", version)
    app.version = version
    redisHandle.set(app.config.gameName + 'version' + app.env, version)
    let versions = version.split('.')
    let maxMax = Number(versions[0])
    let maxMin = Number(versions[1])
    await mongodbHandle.versionDao.updateOne({
        maxVersion: maxMax,
        minVersion: maxMin
    }, {
        $set: {
            maxVersion: maxMax,
            minVersion: maxMin,
            data: data,
            time: new Date().getTime(),
            modify: modify || 0
        }
    }, {
        upsert: true
    })
    if (cluster.isMaster) {
        for (const id in cluster.workers) {
            let worker = cluster.workers[id]
            if (worker) {
                worker.send({ "message": 'setVersion', version: version })
            }
        }
        // app.arenaFork.send({ "message": "version", "version": app.version });
        // app.csFork.send({ "message": "version", "version": app.version });
    }
    return { err: 0 }

})

function getResData(data) {
    data = JSON.stringify(data)
    if (app.env == 'pro' || app.env == "demo") {
        data = base64.encode(data)
    }
    return data
}

function getRespData(str) {
    let data = ''
    if (app.env == 'pro' || app.env == "demo") {
        data = base64.decode(str)
    }
    return data
}

routes.setNotLogin('aList', [
    ['gid', 'string'],
    ['platform', 'string']
], async (msg, cb) => {
    let { gid, platform } = msg
    let data = {}
    return new Promise(resolve => {
        // fetch( `http://share.qihuan.tech/share/game/aList`, {
        //     method: 'POST',
        //     body: JSON.stringify()
        // })
        request.post({
            url: `http://share.qihuan.tech/share/game/aList`,
            headers: {
            },
            body: JSON.stringify({ gid, platform }),
        },
            function (error, response, body) {
                try {
                    console.log(error)
                    data = body
                    resolve({ err: 0, data })
                } catch (er) {
                    console.log(er)
                }
            }
        );
    })
})

routes.setNotLogin('setServerState', [
    ['serverState', 'number'],
    ['stateText', 'string']
], async (msg, cb) => {
    app.serverState = msg.serverState
    app.stateText = msg.stateText || "服务器在维护中"
    if (cluster.isMaster) {
        for (const id in cluster.workers) {
            let worker = cluster.workers[id]
            worker.send({ "message": 'setServerState', serverState: app.serverState, stateText: app.stateText })
        }
    }
    return { err: 0 }
})

routes.setUserNotLogin('getVersionData', [
    ['max', 'number'],
    ['min', 'number'],
], async (msg, cb) => {
    let {
        max,
        min,
    } = msg
    let doc = await mongodbHandle.versionDao.findOne({
        maxVersion: max,
        minVersion: min
    })
    let data = []
    if (doc && doc.data) {
        data = doc.data
    }
    return { err: 0, data: data }
})

routes.setUserNotLogin('setCheat', [
    ['pID', 'string'],
    ['cheat', 'boolean'],
], async (msg, cb) => {
    let {
        pID,
        cheat
    } = msg
    let myData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (myData) {
        await mongodbHandle.playerDao.updateOne({
            _id: ObjectId(pID)
        }, {
            $set: {
                cheat: cheat
            }
        })
    }
    return { err: 0 }
})

routes.setUserNotLogin('getVersionDatas', [], async (msg, cb) => {
    let docs = await mongodbHandle.versionDao.findByPageAndSort({
        modify: {
            $gte: 1
        }
    }, {
        maxVersion: -1,
        minVersion: -1
    }, 0, 25)
    return { err: 0, data: docs }
})


// //充值
// routes.setUserNotLogin('charge', [
//     ['productID', 'any'],
//     ['pID', 'any'],
//     ['amount', 'any'],
//     ['orderID', 'any'],
// ], async (msg, session, cb) => {
//     let {
//         productID, pID, amount, orderID
//     } = msg

//     let doc = await mongodbHandle.chargeDao.findOne({ orderID: orderID })
//     if (!doc) {
//         await mongodbHandle.chargeDao.newAndSave(orderID, pID, amount, productID)
//     } else if (doc && doc.isPay) {
//         return { err: 1 }
//     }
//     let flag = false
//     if (productID) {
//         let playerDoc = await mongodbHandle.playerDao.findOne({ id: pID })
//         if (!playerDoc) {
//             return { err: 2 }
//         }
//         if (productID === "wuxiamoth") {
//             let vipTime = (playerDoc.vipTime || new Date().getTime())
//             if (vipTime < moment().valueOf()) {
//                 vipTime = moment().valueOf()
//             }
//             vipTime += 30 * amount * 24 * 60 * 60 * 1000
//             await mongodbHandle.playerDao.updateOne({
//                 id: pID
//             }, {
//                 $set: {
//                     vipTime: vipTime
//                 }
//             })
//             flag = true
//         } else if (productID === "wuxiagift") {
//             let gold = ['gold', 1000 * amount]
//             let items1 = [gold, ['vipExp', 20 * amount], [170010, 2 * amount], [170011, 1 * amount]]
//             let items2 = [{ "tID": 175001, "lvl": 0, "stack": amount, "pos": 0, "hp": 2, "new": 0, "lock": 0, "price": 0, "kind": "", "equipment": null, "treasure": null, "pet": null, "skill": null },
//             { "tID": 175002, "lvl": 0, "stack": amount, "pos": 0, "hp": 2, "new": 0, "lock": 0, "price": 0, "kind": "", "equipment": null, "treasure": null, "pet": null, "skill": null },
//             { "tID": 175003, "lvl": 0, "stack": amount, "pos": 0, "hp": 2, "new": 0, "lock": 0, "price": 0, "kind": "", "equipment": null, "treasure": null, "pet": null, "skill": null },
//             { "tID": 175004, "lvl": 0, "stack": amount, "pos": 0, "hp": 2, "new": 0, "lock": 0, "price": 0, "kind": "", "equipment": null, "treasure": null, "pet": null, "skill": null }]
//             mongodbHandle.mailDao.newAndSave(playerDoc._id.toString(), '侠客礼包x' + amount, items1, items2)
//             flag = true
//         }

//     }
//     if (flag) {
//         await mongodbHandle.chargeDao.updateOne({ orderID: orderID }, {
//             $set: {
//                 isPay: true,
//             }
//         })
//     }
//     return { err: 0 }
// })

//充值
routes.setUserNotLogin('notifycharge', [
    ['trade_status', 'string'],
    ['pid', 'string', false],
    ['out_trade_no', 'string'],
    ['trade_no', 'string', false],
    ['money', 'string', false],
    ['type', 'string', false],
    ['name', 'string', false],
    ['sign', 'string', false],
    ['sign_type', 'string', false],
], async (msg, session, cb) => {
    let {
        trade_status, pid, out_trade_no, trade_no, money, type, name, sign, sign_type
    } = msg
    if (!trade_status) {
        return { err: 1 }
    }
    let doc = await mongodbHandle.chargeDao.findOne({ orderID: out_trade_no })
    if (!doc) {
        return { err: 2 }
    }
    if (doc.isPay) {
        return { err: 3 }
    }
    await mongodbHandle.chargeDao.updateOne({ orderID: out_trade_no }, {
        $set: {
            isPay: true,
        }
    })
    //********** */
    if (doc.productID) {
        // let player = await mongodbHandle.playerDao.findOne({ _id: ObjectId(doc.pID) })
        // let amount = 0
        // if (doc.productID == 4) {
        //     amount = 10
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "冒险礼包", [[20030970, 1]], 0, 0)
        // } else if (doc.productID == 5) {
        //     amount = 50
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "5个冒险礼包", [[20030970, 5]], 0, 0)
        // } else if (doc.productID == 6) {
        //     amount = 100
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "10个冒险礼包", [[20030970, 10]], 0, 0)
        // } else if (doc.productID == 7) {
        //     amount = 300
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "30个冒险礼包", [[20030970, 30]], 0, 0)
        // } else if (doc.productID == 8) {
        //     amount = 500
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "50个冒险礼包", [[20030970, 50]], 0, 0)
        // } else if (doc.productID == 11) {
        //     amount = 50
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "1个八月礼包", [[20030978, 1]], 0, 0)
        //     let time = moment().startOf('day').valueOf()
        //     await mongodbHandle.playerDao.updateOne({
        //         _id: ObjectId(doc.pID)
        //     }, {
        //         $set: {
        //             giftTime: time,
        //             giftBuyTims: time == player.giftTime ? (player.giftBuyTims || 0) + 1 : 1
        //         }
        //     })
        // } else if (doc.productID == 12) {
        //     amount = 50
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "1个八月礼包", [[20030978, 1]], 0, 0)
        //     let time = moment().startOf('day').valueOf()
        //     await mongodbHandle.playerDao.updateOne({
        //         _id: ObjectId(doc.pID)
        //     }, {
        //         $set: {
        //             giftTime: time,
        //             giftBuyTims: time == player.giftTime ? (player.giftBuyTims || 0) + 1 : 1
        //         }
        //     })
        // } else if (doc.productID == 13) {
        //     amount = 100
        //     let time = moment().startOf('day').valueOf()
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "2个八个月礼包", [[20030978, 2]], 0, 0)
        //     await mongodbHandle.playerDao.updateOne({
        //         _id: ObjectId(doc.pID)
        //     }, {
        //         $set: {
        //             giftTime: time,
        //             giftBuyTims: time == player.giftTime ? (player.giftBuyTims || 0) + 2 : 2
        //         }
        //     })
        // } else if (doc.productID == 14) {
        //     amount = 300
        //     let time = moment().startOf('day').valueOf()
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "6个八个月礼包", [[20030978, 5]], 0, 0)
        //     await mongodbHandle.playerDao.updateOne({
        //         _id: ObjectId(doc.pID)
        //     }, {
        //         $set: {
        //             giftTime: time,
        //             giftBuyTims: time == player.giftTime ? (player.giftBuyTims || 0) + 5 : 5
        //         }
        //     })
        // }  else if (doc.productID == 15) {
        //     amount = 500
        //     let time = moment().startOf('day').valueOf()
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "10个八个月礼包", [[20030978, 10]], 0, 0)
        //     await mongodbHandle.playerDao.updateOne({
        //         _id: ObjectId(doc.pID)
        //     }, {
        //         $set: {
        //             giftTime: time,
        //             giftBuyTims: time == player.giftTime ? (player.giftBuyTims || 0) + 10 : 10
        //         }
        //     })
        // } else  if (doc.productID == 21) {
        //     amount = 10
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "钻石礼包", null, 600, 0)
        // } else if (doc.productID == 22) {
        //     amount = 50
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "5个钻石礼包", null, 3000, 0)
        // } else if (doc.productID == 23) {
        //     amount = 100
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "10个钻石礼包", null, 6000, 0)
        // } else if (doc.productID == 24) {
        //     amount = 300
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "30个钻石礼包", null, 18000, 0)
        // } else if (doc.productID == 25) {
        //     amount = 500
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "50个钻石礼包", null, 30000, 0)
        // } else  if (doc.productID == 26) {
        //     amount = 10
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "材料礼包", [[20030976, 1]], 0, 0)
        // } else if (doc.productID == 27) {
        //     amount = 50
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "5个材料礼包", [[20030976, 5]], 0, 0)
        // } else if (doc.productID == 28) {
        //     amount = 100
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "10个材料礼包", [[20030976, 10]], 0, 0)
        // } else if (doc.productID == 29) {
        //     amount = 300
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "30个材料礼包", [[20030976, 30]], 0, 0)
        // } else if (doc.productID == 30) {
        //     amount = 500
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "50个材料礼包", [[20030976, 50]], 0, 0)
        // }
        // if (amount > 0) {
        //     await mongodbHandle.playerDao.updateOne({
        //         _id: ObjectId(doc.pID)
        //     }, {
        //         $set: {
        //             chargeMoney: (player.chargeMoney || 0) + amount
        //         }
        //     })
        // }
    }
    return { err: 0 }
})


//充值
routes.setUserNotLogin('leNotifycharge', [
    ['order_id', 'string'],
    ['pay_money', 'string', false],
    ['pay_time', 'string', false],
    ['exinfo', 'string', false],
    ['sign', 'string', false],
    ['role_id', 'string', false],
], async (msg, session) => {
    let {
        order_id, pay_money, pay_time, exinfo, payKey
    } = msg
    if (!exinfo) {
        return {
            err: 0, data: {
                "errno": 2,
                "msg": "exinfo不正确"
            }
        }
    }
    let doc = await mongodbHandle.chargeDao.findOne({ orderID: exinfo })
    if (!doc) {
        return {
            err: 0, data: {
                "errno": 3,
                "msg": "订单不存在"
            }
        }
    }
    if (doc.isPay) {
        return {
            err: 0, data: {
                "errno": 1,
                "msg": "订单已经发货"
            }
        }
    }
    await mongodbHandle.chargeDao.updateOne({ orderID: exinfo }, {
        $set: {
            isPay: true,
        }
    })
    //********** */
    if (doc.productID) {
        // let player = await mongodbHandle.playerDao.findOne({ _id: ObjectId(doc.pID) })
        // let amount = 0
        // if (doc.productID == 4) {
        //     amount = 10
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "冒险礼包", [[20030970, 1]], 0, 0)
        // } else if (doc.productID == 5) {
        //     amount = 50
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "5个冒险礼包", [[20030970, 5]], 0, 0)
        // } else if (doc.productID == 6) {
        //     amount = 100
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "10个冒险礼包", [[20030970, 10]], 0, 0)
        // } else if (doc.productID == 7) {
        //     amount = 300
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "30个冒险礼包", [[20030970, 30]], 0, 0)
        // } else if (doc.productID == 8) {
        //     amount = 500
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "50个冒险礼包", [[20030970, 50]], 0, 0)
        // } else if (doc.productID == 11) {
        //     amount = 50
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "1个八月礼包", [[20030978, 1]], 0, 0)
        //     let time = moment().startOf('day').valueOf()
        //     await mongodbHandle.playerDao.updateOne({
        //         _id: ObjectId(doc.pID)
        //     }, {
        //         $set: {
        //             giftTime: time,
        //             giftBuyTims: time == player.giftTime ? (player.giftBuyTims || 0) + 1 : 1
        //         }
        //     })
        // } else if (doc.productID == 12) {
        //     amount = 50
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "1个八月礼包", [[20030978, 1]], 0, 0)
        //     let time = moment().startOf('day').valueOf()
        //     await mongodbHandle.playerDao.updateOne({
        //         _id: ObjectId(doc.pID)
        //     }, {
        //         $set: {
        //             giftTime: time,
        //             giftBuyTims: time == player.giftTime ? (player.giftBuyTims || 0) + 1 : 1
        //         }
        //     })
        // } else if (doc.productID == 13) {
        //     amount = 100
        //     let time = moment().startOf('day').valueOf()
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "2个八个月礼包", [[20030978, 2]], 0, 0)
        //     await mongodbHandle.playerDao.updateOne({
        //         _id: ObjectId(doc.pID)
        //     }, {
        //         $set: {
        //             giftTime: time,
        //             giftBuyTims: time == player.giftTime ? (player.giftBuyTims || 0) + 2 : 2
        //         }
        //     })
        // } else if (doc.productID == 14) {
        //     amount = 300
        //     let time = moment().startOf('day').valueOf()
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "6个八个月礼包", [[20030978, 6]], 0, 0)
        //     await mongodbHandle.playerDao.updateOne({
        //         _id: ObjectId(doc.pID)
        //     }, {
        //         $set: {
        //             giftTime: time,
        //             giftBuyTims: time == player.giftTime ? (player.giftBuyTims || 0) + 6 : 6
        //         }
        //     })
        // }  else if (doc.productID == 15) {
        //     amount = 500
        //     let time = moment().startOf('day').valueOf()
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "10个八个月礼包", [[20030978, 10]], 0, 0)
        //     await mongodbHandle.playerDao.updateOne({
        //         _id: ObjectId(doc.pID)
        //     }, {
        //         $set: {
        //             giftTime: time,
        //             giftBuyTims: time == player.giftTime ? (player.giftBuyTims || 0) + 10 : 10
        //         }
        //     })
        // } else  if (doc.productID == 21) {
        //     amount = 10
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "钻石礼包", null, 600, 0)
        // } else if (doc.productID == 22) {
        //     amount = 50
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "5个钻石礼包", null, 3000, 0)
        // } else if (doc.productID == 23) {
        //     amount = 100
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "10个钻石礼包", null, 6000, 0)
        // } else if (doc.productID == 24) {
        //     amount = 300
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "30个钻石礼包", null, 18000, 0)
        // } else if (doc.productID == 25) {
        //     amount = 500
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "50个钻石礼包", null, 30000, 0)
        // } else  if (doc.productID == 26) {
        //     amount = 10
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "材料礼包", [[20030976, 1]], 0, 0)
        // } else if (doc.productID == 27) {
        //     amount = 50
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "5个材料礼包", [[20030976, 5]], 0, 0)
        // } else if (doc.productID == 28) {
        //     amount = 100
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "10个材料礼包", [[20030976, 10]], 0, 0)
        // } else if (doc.productID == 29) {
        //     amount = 300
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "30个材料礼包", [[20030976, 30]], 0, 0)
        // } else if (doc.productID == 30) {
        //     amount = 500
        //     await mongodbHandle.mailDao.newAndSave(doc.pID, "50个材料礼包", [[20030976, 50]], 0, 0)
        // }
        // if (amount > 0) {
        //     await mongodbHandle.playerDao.updateOne({
        //         _id: ObjectId(doc.pID)
        //     }, {
        //         $set: {
        //             chargeMoney: (player.chargeMoney || 0) + amount
        //         }
        //     })
        // }
    }
    return {
        err: 0, data: {
            "errno": 1,
            "msg": "成功"
        }
    }
})


//充值
routes.setUserNotLogin('leNotifychargeTest', [
    ['order_id', 'string'],
    ['pay_money', 'string', false],
    ['pay_time', 'string', false],
    ['exinfo', 'string', false],
    ['sign', 'string', false],
    ['role_id', 'string', false],
], async (msg, session, cb) => {
    return {
        "errno": 1,
        "msg": "成功"
    }
})

const Token = "Vo1NIIzyAEQg43vo4InPsq4r0u471viO"

// let chargetTypes = {
//     1: { name: '月卡', money: 30.00 },
//     2: { name: '季卡', money: 80.00 },
//     3: { name: '半年卡', money: 150.00 }
// }


// routes.setLogin('pay', [
//     ['index', 'number'],
//     ['type', 'number']
// ], async (msg, session, cb) => {
//     let {
//         index,
//         type
//     } = msg
//     let chargetType
//     if (app.env == "pro") {
//         let chargetTypes = {
//             1: { name: 'month', money: 30.00 },
//             2: { name: 'season', money: 80.00 },
//             3: { name: 'halfyear', money: 150.00 },
//             4: { name: 'fantasy', money: 10.00 },
//             5: { name: 'fantasy5', money: 50.00 },
//             6: { name: 'fantasy10', money: 100.00 },
//             7: { name: 'fantasy30', money: 300.00 },
//             8: { name: 'fantasy50', money: 500.00 },
//             11: { name: 'materials', money: 10.00 },
//             12: { name: 'materials5', money: 50.00 },
//             13: { name: 'materials10', money: 100.00 },
//             14: { name: 'materials30', money: 300.00 },
//             15: { name: 'materials50', money: 500.00 },
//             21: { name: 'diamond', money: 10.00 },
//             22: { name: 'diamond5', money: 50.00 },
//             23: { name: 'diamond10', money: 100.00 },
//             24: { name: 'diamond30', money: 300.00 },
//             25: { name: 'diamond50', money: 500.00 },
//             26: { name: 'material', money: 10.00 },
//             27: { name: 'material5', money: 50.00 },
//             28: { name: 'material10', money: 100.00 },
//             29: { name: 'material30', money: 300.00 },
//             30: { name: 'material50', money: 500.00 },
//         }
//         chargetType = chargetTypes[index]
//     } else {
//         let chargetTypes = {
//             1: { name: 'month', money: 0.01 },
//             2: { name: 'season', money: 0.01 },
//             3: { name: 'halfyear', money: 0.01 },
//             4: { name: 'fantasy', money: 10.00 },
//             5: { name: 'fantasy5', money: 50.00 },
//             6: { name: 'fantasy10', money: 100.00 },
//             7: { name: 'fantasy30', money: 300.00 },
//             8: { name: 'fantasy50', money: 500.00 },
//             11: { name: 'materials', money: 10.00 },
//             12: { name: 'materials5', money: 50.00 },
//             13: { name: 'materials10', money: 100.00 },
//             14: { name: 'materials30', money: 300.00 },
//             15: { name: 'materials50', money: 500.00 },
//             21: { name: 'diamond', money: 10.00 },
//             22: { name: 'diamond5', money: 50.00 },
//             23: { name: 'diamond10', money: 100.00 },
//             24: { name: 'diamond30', money: 300.00 },
//             25: { name: 'diamond50', money: 500.00 },
//             26: { name: 'material', money: 10.00 },
//             27: { name: 'material5', money: 50.00 },
//             28: { name: 'material10', money: 100.00 },
//             29: { name: 'material30', money: 300.00 },
//             30: { name: 'material50', money: 500.00 },
//         }
//         chargetType = chargetTypes[index]
//     }
//     if (!chargetType) {
//         return { err: 1 }
//     }
//     if (type !== 1 && type !== 2) {
//         return { err: 1 }
//     }
//     let orderID = utils.randomString(16)
//     // let goodsname = Goodsname[index]
//     let orderuid = session.pID
//     // let str = `${goodsname}${istype}${app.config.pay_notify_url}${orderID}${orderuid}${money}${app.config.pay_return_url}${Token}${Uid}`
//     // var md5Value = utility.md5(str);
//     type = type == 1 ? "alipay" : "wxpay"
//     let money = chargetType.money
//     let pid = 265199
//     let name = chargetType.name
//     let str = `money=${money}&name=${name}&notify_url=${app.config.pay_notify_url}&out_trade_no=${orderID}&pid=${pid}&return_url=${app.config.pay_return_url}&type=${type}${Token}${Token}`
//     var md5Value = utility.md5(str);
//     await mongodbHandle.chargeDao.newAndSave(orderID, session.uID, session.pID, money, index)
//     return {
//         err: 0,
//         data: {
//             pid: pid,
//             out_trade_no: orderID,
//             money: money,
//             type: type,
//             notify_url: app.config.pay_notify_url,
//             return_url: app.config.pay_return_url,
//             name: chargetType.name,
//             // sitename: '奇幻冒险',
//             sign: md5Value
//         }
//     }
// })


// routes.setLogin('pay2', [
//     ['index', 'number'],
// ], async (msg, session, cb) => {
//     let {
//         index
//     } = msg
//     let chargetType
//     if (app.env == "pro") {
//         let chargetTypes = {
//             4: { name: 'fantasy', money: 10.00 },
//             5: { name: 'fantasy5', money: 50.00 },
//             6: { name: 'fantasy10', money: 100.00 },
//             7: { name: 'fantasy30', money: 300.00 },
//             8: { name: 'fantasy50', money: 500.00 },
//             11: { name: 'materials', money: 10.00 },
//             12: { name: 'materials5', money: 50.00 },
//             13: { name: 'materials10', money: 100.00 },
//             14: { name: 'materials30', money: 300.00 },
//             15: { name: 'materials50', money: 500.00 },
//             21: { name: 'diamond', money: 10.00 },
//             22: { name: 'diamond5', money: 50.00 },
//             23: { name: 'diamond10', money: 100.00 },
//             24: { name: 'diamond30', money: 300.00 },
//             25: { name: 'diamond50', money: 500.00 },
//             26: { name: 'material', money: 10.00 },
//             27: { name: 'material5', money: 50.00 },
//             28: { name: 'material10', money: 100.00 },
//             29: { name: 'material30', money: 300.00 },
//             30: { name: 'material50', money: 500.00 },
//         }
//         chargetType = chargetTypes[index]
//     } else {
//         let chargetTypes = {
//             4: { name: 'fantasy', money: 0.01 },
//             5: { name: 'fantasy5', money: 0.01 },
//             6: { name: 'fantasy10', money: 0.01 },
//             7: { name: 'fantasy30', money: 0.01 },
//             8: { name: 'fantasy50', money: 500.00 },
//             11: { name: 'materials', money: 10.00 },
//             12: { name: 'materials5', money: 50.00 },
//             13: { name: 'materials10', money: 100.00 },
//             14: { name: 'materials30', money: 300.00 },
//             15: { name: 'materials50', money: 500.00 },
//             21: { name: 'diamond', money: 10.00 },
//             22: { name: 'diamond5', money: 50.00 },
//             23: { name: 'diamond10', money: 100.00 },
//             24: { name: 'diamond30', money: 300.00 },
//             25: { name: 'diamond50', money: 500.00 },
//             26: { name: 'material', money: 10.00 },
//             27: { name: 'material5', money: 50.00 },
//             28: { name: 'material10', money: 100.00 },
//             29: { name: 'material30', money: 300.00 },
//             30: { name: 'material50', money: 500.00 },
//         }
//         chargetType = chargetTypes[index]
//     }
//     if (!chargetType) {
//         return { err: 1 }
//     }
//     let orderID = utils.randomString(17)
//     // let goodsname = Goodsname[index]
//     let orderuid = session.pID
//     // let str = `${goodsname}${istype}${app.config.pay_notify_url}${orderID}${orderuid}${money}${app.config.pay_return_url}${Token}${Uid}`
//     // var md5Value = utility.md5(str);
//     let money = chargetType.money
//     let name = chargetType.name

//     await mongodbHandle.chargeDao.newAndSave(orderID, session.uID, session.pID, money, index, '乐辰')
//     return {
//         err: 0,
//         data: {
//             orderID: orderID,
//             money: money,
//             name: chargetType.name,
//         }
//     }

// })

routes.setUserNotLogin('getInterface', null, async (data) => {
    return {
        err: 0, data: {
            login: Object.keys(routes.login),
            userNotLogin: Object.keys(routes.userNotLogin),
            notLogin: Object.keys(routes.notLogin),
            validationData: routes.validationData,
        }
    }
})

routes.setLogin('getT', [], async (msg, session) => {
    return {
        err: 0, data: {
            version: app.version,
            minVersion: app.minVersion
        }
    }
})

routes.setLogin('getEvent', [], async (msg, session) => {
    let data = await worldBossHandle.worldBossEvent(session.serverID, session.pID)
    return {
        err: 0,
        data: data
    }
})

routes.setLogin('battleWorldBoss', [
    ["eventId", "string"],
    ["damage", "number"]
], async (msg, session) => {
    let { eventId, damage } = msg
    let data = await worldBossHandle.battleWorldBoss(session.serverID, eventId, session.pID, damage)
    return {
        err: 0,
        data
    }
})

routes.setLogin('worldBossRank', [
    ["eventId", "string"],
], async (msg, session) => {
    let { eventId } = msg
    let data = await worldBossHandle.worldBossRank(session.serverID, eventId, session.pID)
    return {
        err: 0,
        data: data
    }
})

//充值
routes.setUserNotLogin('charge', [
    ['productID', 'any'],
    ['pID', 'any'],
    ['amount', 'any'],
    ['orderID', 'any'],
], async (msg, session, cb) => {
    let {
        productID, pID, amount, orderID
    } = msg
    console.log('充值数据', msg)
    let doc = await mongodbHandle.chargeDao.findOne({ orderID: orderID })
    if (!doc) {
        await mongodbHandle.chargeDao.newAndSave(orderID, pID, amount, productID)
    } else if (doc && doc.isPay) {
        return { err: 1 }
    }
    let flag = false
    if (productID) {
        let playerDoc = await mongodbHandle.playerDao.findOne({ id: pID })
        if (!playerDoc) {
            return { err: 2 }
        }
        if (productID === "xiangshumoth") {
            let vipTime = (playerDoc.vipTime || new Date().getTime())
            if (vipTime < moment().valueOf()) {
                vipTime = moment().valueOf()
            }
            vipTime += 30 * amount * 24 * 60 * 60 * 1000
            await mongodbHandle.playerDao.updateOne({
                id: pID
            }, {
                $set: {
                    vipTime: vipTime
                }
            })
            await mongodbHandle.mailDao.newAndSave(playerDoc._id.toString(), `尊敬的玩家,充值幻想日记月卡${amount}个月成功,请重新登陆刷新月卡时间`, null, null)
            flag = true
        } else if (productID === "xiangshugift") {
            let playerDoc = await mongodbHandle.playerDao.findOne({ id: pID })
            if (!playerDoc) {
                console.log(`ID:${pID}不存在,发送礼包失败`)
            }
            await mongodbHandle.mailDao.newAndSave(playerDoc._id.toString(), `勇者礼包`, [["diamond", 1000 * amount], ['gold', amount * 20000], ['vipExp', amount * 20]], null)
            flag = true

            let doc = await mongodbHandle.playerDao.findOne({ _id: playerDoc._id })
            if (doc) {
                let day = moment().startOf('day').valueOf()

                await mongodbHandle.playerDao.updateOne({
                    _id: playerDoc._id
                }, {
                    $set: {
                        chargeMoney: (doc.chargeMoney || 0) + 20 * amount,
                        unStatDay: day
                    }
                })
            }
        } else if (productID === "xiangshulong") {
            let playerDoc = await mongodbHandle.playerDao.findOne({ id: pID })
            if (!playerDoc) {
                console.log(`ID:${pID}不存在,发送礼包失败`)
            }
            let exists = await mongodbHandle.playerAndGiftDao.findOne({ pID: pID, giftID: 'xiangshulong' })
            if (exists) {
                console.log(`ID:${pID}重复购买,发送礼包失败`)
            }
            await mongodbHandle.playerAndGiftDao.newAndSave(pID, 'xiangshulong')
            flag = true
            let doc = await mongodbHandle.playerDao.findOne({ _id: playerDoc._id })
            if (doc) {
                let day = moment().startOf('day').valueOf()

                await mongodbHandle.playerDao.updateOne({
                    _id: playerDoc._id
                }, {
                    $set: {
                        chargeMoney: (doc.chargeMoney || 0) + 98,
                        unStatDay: day,
                        longVip: true
                    }
                })
                await mongodbHandle.mailDao.newAndSave(doc._id.toString(), '荣耀卡', [["longVip", 1], ['vipExp', 98]], null)
            } else if (productID === "xiangshunew") {
                let playerDoc = await mongodbHandle.playerDao.findOne({ id: pID })
                if (!playerDoc) {
                    console.log(`ID:${pID}不存在,发送礼包失败`)
                }
                let exists = await mongodbHandle.playerAndGiftDao.findOne({ pID: pID, giftID: 'xiangshunew' })
                if (exists) {
                    console.log(`ID:${pID}重复购买,发送礼包失败`)
                }
                await mongodbHandle.playerAndGiftDao.newAndSave(pID, 'xiangshunew')
                await mongodbHandle.mailDao.newAndSave(playerDoc._id.toString(), `新人福利礼包`, [['gold', 5000000], ["diamond", 10000], [170008, 100], [170018, 1000], [170005, 1000], [175001, 3, 5], [175002, 3, 5], [175003, 3, 5], [175004, 3, 5]], null)
                flag = true
                let doc = await mongodbHandle.playerDao.findOne({ _id: playerDoc._id })
                if (doc) {
                    let day = moment().startOf('day').valueOf()

                    await mongodbHandle.playerDao.updateOne({
                        _id: playerDoc._id
                    }, {
                        $set: {
                            chargeMoney: (doc.chargeMoney || 0) + 100,
                            unStatDay: day,
                            newUserGift: 1
                        }
                    })
                }
            }
        }

    }
    if (flag) {
        await mongodbHandle.chargeDao.updateOne({ orderID: orderID }, {
            $set: {
                isPay: true
            }
        })
    }
    return {
        err: 0
    }
})